import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import minidraw.framework.Drawing;
import minidraw.framework.DrawingEditor;
import minidraw.framework.Figure;
import minidraw.framework.Tool;


public class SwitchTool implements Tool {
	
	private DrawingEditor editor;
	private PuzzleGame game;
	private Figure previous;
	private Figure current;
	private Position currPos;

	public SwitchTool(DrawingEditor editor, PuzzleGame game) {
		this.editor = editor;
		this.game = game;
		previous = current = null;
	}

	@Override
	public void keyDown(KeyEvent e, int key) {	}

	@Override
	public void mouseDown(MouseEvent e, int x, int y) {
		Drawing model = editor.drawing();
		model.lock();
		
		Position nullPos = game.getNullPos();
		Position tmpPos = game.getPosition(e.getY(), e.getX());
		Figure tmp = model.findFigure(e.getY(), e.getX());
		if(previous == null && current == null) { 
			if(nullPos.equals(tmpPos)) {
				current = tmp;
				currPos = tmpPos;
				System.out.println("Selected null position:" + nullPos);
			}
		} else if(nullPos.equals(currPos) && game.isNextTo(currPos, tmpPos)) {
				previous = current;
				current = tmp;
				game.move(currPos, tmpPos);
				previous.changed();
				current.changed();
				System.out.println("Moved null position from " + currPos + " to " + tmpPos);
				currPos = null;
				previous = null;
				current = null;
		}
		
		model.unlock();
	}

	@Override
	public void mouseDrag(MouseEvent e, int x, int y) {	}

	@Override
	public void mouseMove(MouseEvent e, int x, int y) {	}

	@Override
	public void mouseUp(MouseEvent e, int arg1, int arg2) {
		//editor.drawing().unlock();
	}

}
